package com.yitiao.service;

import com.yitiao.feign.OrderFeignClient;
import com.yitiao.feign.StockFeignClient;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class BusinessServiceImpl implements BusinessService {

    private final StockFeignClient stockFeignClient;

    private final OrderFeignClient orderFeignClient;

    @Override
    @GlobalTransactional(timeoutMills = 60000)
    public void purchase(String userId, String commodityCode, int orderCount, boolean rollback) {
        String result = stockFeignClient.deduct(commodityCode, orderCount);

        if (!"SUCCESS".equals(result)) {
            throw new RuntimeException("库存服务调用失败,事务回滚!");
        }
        result = orderFeignClient.create(userId, commodityCode, orderCount);
        if (!"SUCCESS".equals(result)) {
            throw new RuntimeException("订单服务调用失败,事务回滚!");
        }

        if (rollback) {
            throw new RuntimeException("Force rollback ... ");
        }
    }
}
